import { useRef, useEffect } from 'react'
import { useGLTF, useAnimations } from '@react-three/drei'
import { useFrame } from '@react-three/fiber'
import * as THREE from 'three'

// 正确预加载
useGLTF.preload('/assets/models/DNA.glb')

export function DNAModel() {
  const group = useRef()

  // ✅ Hook 必须在组件顶层调用
  const { scene, animations } = useGLTF('/assets/models/DNA.glb')
  const { actions } = useAnimations(animations, group)

  useEffect(() => {
    console.log('DNA Model useEffect triggered')

    if (!scene) {
      console.warn('Scene not loaded')
      return
    }

    // 遍历模型网格，应用新的材质
    scene.traverse((child) => {
      if (child.isMesh) {
        // 创建新的材质
        const newMaterial = new THREE.MeshStandardMaterial({
          color: '#FFFFFF', // 设置为白色
          transparent: true,
          opacity: 0.8,
          envMapIntensity: 1
        });

        // 赋值给网格
        child.material = newMaterial;
      }
    })

    // 输出场景结构
    console.log('Loaded scene:', scene)
    console.log('Children:', scene.children)
    console.log('Animations:', animations)
    console.log('Actions:', actions)
  }, [scene, animations, actions])

  useFrame((_, delta) => {
    if (group.current) {
      group.current.rotation.y += delta * 0.2
    }
  })

  return (
    <group ref={group} dispose={null}>
      <primitive object={scene} scale={2} position={[0, -0.5, 0]} />
    </group>
  )
}
